<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>01.webStorage实现cookie有效期效果</title>
</head>
<body>
    <h1>01.webStorage实现cookie有效期效果</h1>
    <script>
        const originSetItem = Storage.prototype.setItem
        Storage.prototype.setItem = function(key,value,expires){
            if(expires){
                value = JSON.stringify({
                    value,
                    expires: Date.parse(expires)
                })
            }
            // 必须改变this指向
            originSetItem.call(this,key,value)
        }
        const originGetItem = Storage.prototype.getItem
        Storage.prototype.getItem = function(key){
            let data = originGetItem.call(this,key); // null,'hello', '{value,expires}'

            try{
                data = JSON.parse(data)
                if(data && data.expires){
                    // 判断是否过有效期
                    if(data.expires <= Date.now()){
                        data = null;
                        this.removeItem(key)
                    }else{
                        data = data.value
                    }
                }
            }catch(err){

            }

            return data
        }
    </script>
</body>
</html>